const $common = require('../../common/common-req.js');
const router = $common.express.Router();
const requestHandler = require('../../common/request-handler.js');
var CryptoJS = require("crypto-js");
const list = []
/**
 * 注册请求
 * */
router.post('/register', async (req, res) => {
    let param = ['phone', 'password', 'name', 'code'];
    param = $common.getQueryParam(req, 'body', param);
    const token = $common.strLen();
    const src = '/public/images/user-head.png'
    const createTime = new Date();
    const updateTime = new Date();
    let { phone, password, name, code } = param;
    let vital = ['phone', 'password', 'name'];
    let _index = -1
    const _t = list.find((item, index) => {
        if (item.phone === phone) {
            _index = index
            return true
        }
        return false
    })
    if (_t) {
        if (_t.code !== code) {
            res.send($common.setErrorData('验证码不正确!'));
            return
        } else {
            list.splice(_index, 1)
            console.log(list, _index)
        }
    } else {
        res.send($common.setErrorData('请获取验证码!'));
        return
    }
    if (!$common.vitalParam(param, vital)) {
        res.send($common.setErrorData('缺少必须参数!'));
    } else {
        if (await $common.isExit([phone], ['phone'], 'user')) {
            res.send($common.setErrorData('该手机号已经注册，请直接登录!'));
        } else {
            let registerSql = 'insert into user(phone, password, userName, token, src, createTime, updateTime) values(?, ?, ?, ?, ?, ?, ?)';
            let registerArr = [phone, password, name, token, src, createTime, updateTime];
            $common.db_mysql.insert(registerSql, registerArr, (result) => {
                if (result) {
                    $common.resData.data = {};
                    $common.resData.msg = '注册成功!';
                    res.send($common.resData);
                } else {
                    res.send($common.setErrorData('异常，注册失败!'));
                }
            })
        }
    }
});

/**
 * 登录请求
 * */
router.post('/login', (req, res) => {
    let param = ['phone', 'password'];
    req.body.phone = $common.enCodePWD(req.body.phone, req.body.k1.substr(0, 6)).substring(10)
    req.body.password = $common.enCodePWD(req.body.password, req.body.k1.substr(0, 6)).substring(10)
    param = $common.getQueryParam(req, 'body', param);
    let { phone, password } = param;
    let vital = ['phone', 'password'];
    if (!$common.vitalParam(param, vital)) {
        res.send($common.setErrorData('缺少必须参数!'));
    } else {
        let loginSql = 'select * from user where phone=? and password=?';
        let loginArr = [phone, password];
        $common.db_mysql.select(loginSql, loginArr, result => {
            let resArr = $common.selectHandle(result, ['phone', 'password', 'token', 'userName', 'src', 'type']);
            if (resArr.length > 0) {
                $common.resData.data = {}
                $common.resData.data.userInfo = {
                    phone: resArr[0].phone,
                    userName: resArr[0].userName,
                    src: resArr[0].src,
                    type: resArr[0].type,
                    token: $common.addPWD(resArr[0].phone, resArr[0].token)
                };
                $common.tokenArr.push($common.resData.data.userInfo.token)
                $common.resData.msg = '登录成功!';
                res.send($common.resData);
            } else {
                res.send($common.setErrorData('登录失败，账号或密码错误!'));
            }
        })
    }
})

/**
 * 统一认证
 * */
router.post('/loginCert', (req, res) => {
    console.log('req.body', req.body)
    let param = ['phone', 'password', 'client_id', 'return_url'];
    req.body.phone = $common.enCodePWD(req.body.phone, req.body.k1.substr(0, 6)).substring(10)
    req.body.password = $common.enCodePWD(req.body.password, req.body.k1.substr(0, 6)).substring(10)
    param = $common.getQueryParam(req, 'body', param);
    let { phone, password, client_id, return_url } = param;
    let vital = ['phone', 'password', 'client_id'];
    if (!$common.vitalParam(param, vital)) {
        res.send($common.setErrorData('缺少必须参数!'));
    } else {
        // let loginSql = 'select * from project_user_view where projectId=? and phone=? and password=?';
        let loginSql = 'select * from project_user_view where projectId=? and phone=? and password=?';
        let loginArr = [client_id, phone, password];
        let loginGetArr = ['phone', 'password', 'token', 'userName', 'type']
        $common.db_mysql.select(loginSql, loginArr, result => {
            let resArr = $common.selectHandle(result, loginGetArr);
            if (resArr.length > 0) {
                $common.resData.data = {}
                const _token = $common.addPWD(resArr[0].phone, resArr[0].token)
                if (return_url) {
                    let url = `${return_url}?client_id=client_id&code=${_token}&phone=${resArr[0].phone}&userName=${resArr[0].userName}&type=${resArr[0].type}`
                    $common.resData.data.return_url = url
                } else {
                    $common.resData.data.userInfo = {
                        phone: resArr[0].phone,
                        userName: resArr[0].userName,
                        src: resArr[0].src,
                        type: resArr[0].type,
                        token: _token
                    };
                }
                $common.tokenArr.push(_token)
                $common.resData.msg = '登录成功!';
                res.send($common.resData);
            } else {
                let loginSql = 'select * from user where phone=? and password=?';
                let loginArr = [phone, password];
                $common.db_mysql.select(loginSql, loginArr, result => {
                    let resArr = $common.selectHandle(result, loginGetArr);
                    if (resArr.length > 0) {
                        $common.resData.data = {}
                        if (return_url) {
                            let url = `${return_url}?client_id=client_id&code=${$common.addPWD(resArr[0].phone, resArr[0].token)}&phone=${resArr[0].phone}&userName=${resArr[0].userName}&type=${resArr[0].type}`
                            $common.resData.data.return_url = url
                        } else {
                            $common.resData.data.userInfo = {
                                phone: resArr[0].phone,
                                userName: resArr[0].userName,
                                src: resArr[0].src,
                                type: resArr[0].type,
                                token: $common.addPWD(resArr[0].phone, resArr[0].token)
                            };
                        }
                        $common.tokenArr.push($common.resData.data.userInfo.token)
                        $common.resData.msg = '登录成功!';
                        res.send($common.resData);
                    } else {
                        res.send($common.setErrorData('登录失败，账号或密码错误!'));
                    }
                })
            }
        })
    }
})

/**
 * 密码找回
 * */
router.post('/changePwd', (req, res) => {
    const param = ['phone', 'verification', 'password', 'rePwd'];
    param = $common.getQueryParam(req, 'body', param);
    let { phone, verification, password, rePwd} = param;
    let vital = ['pageNum', 'pageSize'];
    if (!$common.vitalParam(param, vital)) {
        res.send($common.setErrorData('缺少必须参数!'));
    } else {
        let updateSql = 'update users set password=? where phone=?';
        let updateArr = [password, phone];
        $common.db_mysql.select(updateSql, updateArr, result => {
            if (resArr) {
                $common.resData.data = {}
                $common.resData.msg = '修改密码成功!';
                res.send($common.resData);
            } else {
                res.send($common.setErrorData('修改密码失败，验证码错误!'));
            }
        })
    }
})

/**
 * 获取短信验证码
 * */
router.get('/sms', (req, res) => {
    const phone = req.query.phone;
    if(!phone) {
        return;
    }
    const Core = require('@alicloud/pop-core');
    
    var client = new Core({
      accessKeyId: 'LTAI5tALmG4eVQRtkjKKiKnK',
      accessKeySecret: 'Nq2xk5L4N8rFmY3I7mlIKYinaGmcE2',
      endpoint: 'https://dysmsapi.aliyuncs.com',
      apiVersion: '2017-05-25'
    });
    let randomCode = $common.strLen(6, 10);
    let code = {
        code: randomCode
    }
    let obj = {
        phone: phone,
        code: randomCode,
        timer: null
    }
    const _t = list.find(item => {
        return item.phone === phone
    })
    if (_t) {
        _t.code = obj.code
    } else {
        list.push(obj);
    }
    var params = {
      "PhoneNumbers": phone,
      "SignName": "个人网站hr",
      "TemplateCode": "SMS_215350744",
      "TemplateParam": JSON.stringify(code)
    }
    
    var requestOption = {
      method: 'POST'
    };
    client.request('SendSms', params, requestOption).then((result) => {
      console.log(JSON.stringify(result));
      if(result.Code === 'OK') {
          res.send({
              data: null,
              msg: '验证码已发送,注意接收!',
              status: 1,
              code: 200
          })
      } else {
          errorData.msg = '获取验证码失败，请重新获取!'
          res.send(errorData)
      }
    }, (ex) => {
      console.log(ex);
    })
})


/**
 * 根据关键字模糊匹配用户
* */
router.get('/searchUser', (req, res) => {
    req.query['search'] = req.query['search'] ? `%${req.query['search']}%` : ''
    let param = ['search'];
    let vital = ['search'];
    let totalSql = '';
    let expand = [];
    let getSql = 'select * from user where phone like ? or userName like ? order by updateTime';
    let getArr = ['search', 'search'];
    let selectAttr = ['phone', 'userName', 'src'];
    let reName = ['phone', 'userName', 'src'];
    let moduleName = '用户列表';
    requestHandler.getHandler(req, res, param, vital, totalSql, expand, getSql, getArr, selectAttr, reName, moduleName);
})

// 获取所有用户
router.get('/allUser', (req, res) => {
    let param = ['pageNum', 'pageSize'];
    let vital = ['pageNum', 'pageSize'];
    let totalSql = 'select count(*) as count from user';
    let expand = [];
    let getSql = 'select * from user order by updateTime desc limit ?, ?';
    let getArr = [];
    let selectAttr = ['phone', 'userName', 'type', 'token', 'createTime', 'updateTime'];
    let reName = ['phone', 'userName', 'type', 'token', 'createTime', 'updateTime'];
    let moduleName = '用户列表';
    requestHandler.getHandler(req, res, param, vital, totalSql, expand, getSql, getArr, selectAttr, reName, moduleName);
    })
    /**
    * 修改用户信息
    * */
    router.put('/allUser', (req, res) => {
     const updateTime = new Date();
     let param = ['phone', 'userName', 'type', 'token'];
     let vital = ['phone'];
     let expand = { updateTime };
     let updateSql = 'update user set userName=?, `type`=?, token=?, updateTime=? where phone=?';
     let updateArr = ['userName', 'type', 'token', 'updateTime', 'phone'];
     let moduleName = '用户信息';
     requestHandler.putHandler(req, res, param, vital, expand, updateSql, updateArr, moduleName);
})
 
/**
* 添加用户信息
* */
router.post('/allUser', (req, res) => {
    const createTime = new Date();
    const updateTime = new Date();
    const projectId = $common.strLen();
    let param = ['phone', 'userName', 'password', 'type', 'token'];
    let vital = ['phone', 'userName', 'password', 'type'];
    let expand = {projectId, createTime, updateTime};
    let insertSql = 'insert into user(phone, userName, password, `type`, token, createTime, updateTime) values(?, ?, ?, ?, ?, ?, ?)';
    let insertArr = ['phone', 'userName', 'password', 'type', 'token', 'createTime', 'updateTime'];
    let moduleName = '项目信息';
    let isExitArr = ['phone'];
    let exitTableName = 'user';
    requestHandler.postHandler(req, res, param, vital, expand, insertSql, insertArr, moduleName, isExitArr, exitTableName);
})
  
/**
* 删除用户
* */
router.delete('/allUser', (req, res) => {
    let param = ['phone'];
    let vital = ['phone'];
    let expand = [];
    let delSql = 'delete from user where phone=?';
    let delArr = ['phone'];
    let moduleName = '用户信息';
    requestHandler.delHandler(req, res, param, vital, expand, delSql, delArr, moduleName);
})

module.exports = router; 
 